<template>
  <div>
    <button @click="getUserData">获取user表数据</button>
    
    <!-- 加载状态提示 -->
    <div v-if="loading">加载中...</div>
    
    <!-- 错误状态提示 -->
    <div v-else-if="error" class="error">{{ error }}</div>
    
    <!-- 数据表格展示 -->
    <table v-else-if="users.length > 0">
      <thead>
        <tr>
          <th>用户名</th>
          <th>密码</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id || user.username">
          <td>{{ user.username }}</td>
          <td>{{ user.password }}</td>
        </tr>
      </tbody>
    </table>
    
    <!-- 空数据提示 -->
    <div v-else>暂无数据</div>
  </div>
</template>

<script>
import axios from "axios"
export default {
  data() {
    return {
      users: [],      // 存储用户数据
      loading: false, // 加载状态
      error: null     // 错误信息
    };
  },

  methods: {
    async getUserData() {
      // 重置状态
      this.users = [];
      this.loading = true;
      this.error = null;
      
      try {
        const response = await axios.get('http://127.0.0.1/user');
        this.users = response.data;
        console.log('获取数据成功:', this.users);
      } catch (err) {
        this.error = `获取数据失败: ${err.message}`;
        console.error(this.error);
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #f5f5f5;
}

.error {
  color: red;
  margin-top: 10px;
}
</style>
